<?php


namespace app\system\controller\cms;

use app\common\model\cms\FieldModel;
use app\common\model\cms\TableModel;
use app\system\controller\BaseController;

class TableController extends BaseController
{
  /**
   * 不检测权限方法
   * @var array
   */
  protected $noCheck = [];

  /**
   * 权限映射
   * @var array
   */
  protected $mapCheck = [
      '*' => 'index',
  ];

  /**
   * 当前模型
   * @var null
   */
  protected $model = null;
  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->model = new TableModel();
  }

  /**
   * 列表
   * @return array|string
   * @throws \Exception
   */
  public function index()
  {
    $tableName  = $this->request->param('table_name/s', 'article');
    $fieldModel = new FieldModel();
    $tableList  = $this->model->order('show_order asc')->select();
    $fieldList  = $fieldModel->where('table_name', $tableName)->order('show_order asc')->select();
    $this->assign('table_name', $tableName);
    $this->assign('table_list', $tableList);
    $this->assign('field_list', $fieldList);
    return $this->fetch();
  }

  /**
   * 添加表
   * @throws \Exception
   */
  public function add()
  {
    $data = $this->request->param();
    $this->validate($data, [
        'display_name|模型名称' => 'require',
        'table_name|表名' => 'require',
    ]);
    if (isset($data['id'])) unset($data['id']); //去除ID
    $this->model->add($data);
    $this->success('操作成功', url('index', ['table_name' => $data['table_name']]));
  }

  /**
   * 编辑表
   * @throws \Exception
   */
  public function edit()
  {
    $data = $this->request->param();
    $this->validate($data, [
        'display_name|模型名称' => 'require'
    ]);
    $this->model->edit($data);
    $this->success('操作成功', url('index', ['table_name' => $data['table_name']]));
  }

  /**
   * 刷新缓存
   * @throws \Exception
   */
  public function refresh()
  {
    $tableNames = $this->request->param('table_names/a');
    if (empty($tableNames)) $this->error('请选择对应模型');
    foreach ($tableNames as $tableName) {
      $this->model->getInfo($tableName, true);
    }
    $this->success('操作成功');
  }

  /**
   * 删除表
   * @throws \Exception
   */
  public function del()
  {
    $id = $this->request->param('id/d');
    $this->model->del($id);
    $this->success('操作成功');
  }
}